package org.px.gui;

import org.px.domain.LeaveRecord;
import org.px.service.LeaveRecordService;
import org.px.domain.UserIdentity;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class EmployeeMainFrame extends JFrame {
    private JPanel mainPanel;
    private String currentUserId;
    
    public EmployeeMainFrame(UserIdentity user){
        this.currentUserId = user.getUser_id();
        initUI(user);
        setVisible(true);
    }
    
    private void initUI(UserIdentity user) {
        setTitle("员工请假管理系统 - 员工主界面");
        setSize(1600, 1000);  // 窗口尺寸
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        
        // 功能菜单保持不变
        JMenu functionMenu = new JMenu("功能");
        JMenuItem applyLeaveItem = new JMenuItem("申请请假");
        JMenuItem viewLeaveItem = new JMenuItem("查看请假情况");
        
        functionMenu.add(applyLeaveItem);
        functionMenu.add(viewLeaveItem);
        // 删除原分隔线和退出项
        
        // 新增系统菜单
        JMenu systemMenu = new JMenu("系统");
        JMenuItem exitItem = new JMenuItem("退出");
        systemMenu.add(exitItem);
        
        menuBar.add(functionMenu);
        menuBar.add(Box.createHorizontalGlue()); // 将系统菜单推到右侧
        menuBar.add(systemMenu);
        
        // 设置菜单栏到窗体
        setJMenuBar(menuBar);

        // 事件监听迁移到菜单项
        applyLeaveItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openApplyLeaveFrame(user);
            }
        });

        viewLeaveItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                viewLeaveRecords(user);
            }
        });

        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0); // 添加退出系统功能
            }
        });

        // 创建主面板
        mainPanel = new JPanel(new BorderLayout());
        add(mainPanel);
    }

    private void openApplyLeaveFrame(UserIdentity user) {
        ApplyLeaveFrame applyLeaveFrame = new ApplyLeaveFrame(this, user.getUser_id());
        applyLeaveFrame.setVisible(true);
    }

    private void viewLeaveRecords(UserIdentity user) {
        try {
            LeaveRecordService leaveRecordService = new LeaveRecordService();
            List<LeaveRecord> leaveRecords = leaveRecordService.getLeaveRecordsByEmpId(user.getUser_id());
            
            // 动态创建表格组件
            String[] columnNames = {"请假ID", "类型", "开始时间", "结束时间", "天数", "原因", "状态"};
            DefaultTableModel model = new DefaultTableModel(columnNames, 0);
            JTable table = new JTable(model);
            table.setRowHeight(30);
            // 设置表格字体（放大到24号）
            table.setFont(new Font("微软雅黑", Font.PLAIN, 24));  // 修改字体大小
            JScrollPane scrollPane = new JScrollPane(table);
            
            // 创建删除按钮面板
            JPanel buttonPanel = new JPanel();
            JButton deleteBtn = new JButton("删除选中的假条");
            deleteBtn.addActionListener(e -> deleteSelectedLeaveRecord(table, user));
            buttonPanel.add(deleteBtn);
            
            // 清空旧内容并添加组件
            mainPanel.removeAll();
            mainPanel.add(scrollPane, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);
            mainPanel.revalidate();
            mainPanel.repaint();
            
            // 填充数据：添加请假ID作为第一列
            for (LeaveRecord record : leaveRecords) {
                Object[] rowData = {
                    record.getLeave_id(),   // 新增：请假ID
                    record.getLeave_type(),
                    record.getStart_time(),
                    record.getEnd_time(),
                    record.getDuration(),
                    record.getReason(),
                    record.getStatus()
                };
                model.addRow(rowData);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(),
                "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    // 删除选中的请假记录（使用请假ID）
    private void deleteSelectedLeaveRecord(JTable table, UserIdentity user) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的假条", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 获取状态列的值（索引6）
        String status = (String) table.getValueAt(selectedRow, 6);
        if (!"待审批".equals(status)) {
            JOptionPane.showMessageDialog(this, "只能删除'待审批'状态的假条", "操作限制", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 获取请假ID列的值（索引0）
        int leaveId = (int) table.getValueAt(selectedRow, 0);
        try {
            LeaveRecordService service = new LeaveRecordService();
            if (service.deleteLeaveRecord(leaveId, currentUserId)) {
                JOptionPane.showMessageDialog(this, "删除成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                viewLeaveRecords(user); // 刷新表格
            } else {
                JOptionPane.showMessageDialog(this, "删除失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
